<?php

namespace App\Http\Controllers;

use Uuid;
use Redis;
use LucaDegasperi\OAuth2Server\Authorizer;

class UserController extends CommonController
{

    public function __construct(Authorizer $authorizer)
    {
        parent::__construct($authorizer);

        $this->middleware('oauth', ['except' => ['store']]);
        $this->middleware('oauth.checkClient', ['only' => 'store']);
        $this->middleware('validation');
    }

    private static $_validate = [
        'store' => [
            'email' => 'required|email|custom_unique',
            'password' => 'required|min:6|confirmed'
        ],
    ];

    /**
     * todo email unique validate
     *
     * @return [type] [description]
     */
    public function store()
    {
        // user emails set to a set
        // 要写的比较优雅一点
        $email = request('email');
        $rawPassword = request('password');

        $identifier = Uuid::generate(4)->string;

        $hashData = [
            'id'           => $identifier,
            'email'        => $email,
            'password'     => bcrypt($rawPassword),
            'avatar_url'   => '/uploads/images/avatar/default.png',
            'display_name' => strstr($email, '@', true),
            'created_at'   => date('Y-m-d H:i:s'),
            'updated_at'   => date('Y-m-d H:i:s'),
        ];

        Redis::hmset("users:{$identifier}", $hashData);
        // 存储用户邮箱和用户 uuid 对应关系的大哈希
        Redis::hset("email:user", $email, $identifier);

        return $hashData;
    }

    public function profile()
    {
        $uid = $this->authorizer->getResourceOwnerId();

        return $this->fetchUser($uid);
    }

    public function myComment()
    {
        $uid = $this->authorizer->getResourceOwnerId();

        list($offset, $limit) = $this->usePagination();

        return $this->getCommentList("users:{$uid}:comments", $offset, $limit);
    }

}